"""
Django settings for haohuo project.

"""
import environ
import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
ROOT_DIR = environ.Path(__file__) - 2
APPS_DIR = ROOT_DIR.path('apps')
sys.path.insert(0, APPS_DIR.root)
env = environ.Env()
# OS environment variables take precedence over variables from .env
if os.path.exists(ROOT_DIR.path('.env')):
    with open(ROOT_DIR.path('.env').root, encoding='utf-8') as f:
        env.read_env(f)

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5*x7&_p_c#9uzi!x&#6e&^ct2+wupl1tx)miar)2lo(!dl6f25'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool('DJANGO_DEBUG', True)

ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["localhost", "127.0.0.1"])

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersAppConfig',
    'assets.apps.AssetsConfig',
    "gifts.apps.GiftsConfig",
    "imagekit",
    'import_export',
    # 'easyaudit.apps.EasyAuditConfig',
    'auditlog',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 'easyaudit.middleware.easyaudit.EasyAuditMiddleware',
    'auditlog.middleware.AuditlogMiddleware',
]

ROOT_URLCONF = 'haohuo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [ROOT_DIR.path("templates").root],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.static',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'haohuo.wsgi.application'

# Database
DATABASES = {
    'default': env.db('DATABASE_URL', default='sqlite:///db.sqlite3')
}
DATABASES['default']['ATOMIC_REQUESTS'] = True

# Password validation
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

AUTH_USER_MODEL = 'users.User'
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = 'users:account_login'

# Admin Config
ADMIN_URL = env.str('ADMIN_URL', default='admin/')
ADMIN_SITE_TITLE = env.str('ADMIN_SITE_TITLE', default='HO资产管理系统')
ADMIN_SITE_HEADER_LOGO = env.str('ADMIN_SITE_HEADER_LOGO', default='logo.png')
ADMIN_SITE_HEADER_LOGO_STYLE = env.str('ADMIN_SITE_HEADER_LOGO_STYLE', default='height:30px;width:138px')
ADMIN_INDEX_TITLE = 'HO站点管理'

# Security

# SECURITY
SESSION_EXPIRE_AT_BROWSER_CLOSE = env.bool("SESSION_EXPIRE_AT_BROWSER_CLOSE", default=True)
SESSION_COOKIE_AGE = env.int("SESSION_COOKIE_AGE", default=6 * 60 * 60)
SESSION_COOKIE_HTTPONLY = env.bool("SESSION_COOKIE_HTTPONLY", default=True)
CSRF_COOKIE_HTTPONLY = env.bool("CSRF_COOKIE_HTTPONLY", default=True)  # True 不能通过document.cookie读取到csrftoken值
SECURE_BROWSER_XSS_FILTER = env.bool("SECURE_BROWSER_XSS_FILTER", default=True)
X_FRAME_OPTIONS = env.str("DENY", default="DENY")

# Internationalization

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = env.bool("USE_I18N", default=True)

USE_L10N = env.bool("USE_L10N", default=True)

USE_TZ = False

# Static files (CSS, JavaScript, Images)
STATIC_ROOT = env.str("STATIC_ROOT", default=ROOT_DIR.path("staticfiles").root)
STATIC_URL = env.str("STATIC_URL", default='/static/')
STATICFILES_DIRS = [ROOT_DIR.path("static").root]
STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder',
                       'django.contrib.staticfiles.finders.AppDirectoriesFinder',
                       ]
MEDIA_ROOT = str(ROOT_DIR.path("media").root)
MEDIA_URL = "/media/"

LOG_DIR = env.str('LOG_DIR', default=ROOT_DIR.path('logs').root)

if not os.path.isdir(LOG_DIR):
    os.makedirs(LOG_DIR)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'root': {
        'level': 'WARNING',
        'handlers': ['console'],
    },
    'formatters': {
        'verbose': {
            'format': '%(asctime)s [%(process)d] [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] '
                      '[%(module)s:%(funcName)s] [%(levelname)s]-- %(message)s'
        },
        'simple': {
            'format': '%(asctime)s[%(levelname)s]-  %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S'
        },
        'standard': {
            'format': '%(asctime)s [%(module)s:%(funcName)s] [%(levelname)s] -- %(message)s',
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filters': ['require_debug_false'],
            'filename': os.path.join(LOG_DIR, 'haohuo.log'),
            'maxBytes': 1024 * 1024 * 50,
            'backupCount': 10,
            'formatter': 'standard',
        },
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filters': ['require_debug_false'],
            'filename': os.path.join(LOG_DIR, 'error.log'),
            'maxBytes': 1024 * 1024 * 20,
            'backupCount': 20,
            'formatter': 'verbose',
        },
        'request': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_DIR, 'request.log'),
            'maxBytes': 1024 * 1024 * 20,
            'backupCount': 20,
            'formatter': 'standard',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['require_debug_true'],
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console', 'error'],
            'propagate': False,
        },
        'django': {
            'handlers': ['console', 'request', 'error'],
            'propagate': False,
        },
        'django.request': {
            'handlers': ['console', 'request'],
            'level': 'INFO',
            'propagate': False
        },
        'django.security.DisallowedHost': {
            'level': 'ERROR',
            'handlers': ['console', 'error'],
            'propagate': False,
        },
        'KSM': {
            'handlers': ['console', 'default', 'error'],
            'level': 'DEBUG',
        },
    },
}


f = ROOT_DIR.path("haohuo", "local_settings.py")
if os.path.exists(f):
    with open(f, 'rb') as fd:
        exec(fd.read())
